package foodmaterial.config;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import java.util.HashMap;
import java.util.Map;

public class DynamicDataSource extends AbstractRoutingDataSource {
    private static volatile DynamicDataSource instance;
    private static byte[] lock = new byte[0];
    private static Map<Object,Object> dataSourceMap = new HashMap<>();

    public Map<Object, Object> getDataSourceMap() {
        return dataSourceMap;
    }

    public static DynamicDataSource getInstance(){
        if(instance == null){
            synchronized (lock){
                if(instance == null){
                    instance = new DynamicDataSource();
                }
            }
        }
        return instance;
    }

    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        super.afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        Object key = DataSourceContextHolder.getDBType();
        if (!isExistDataSource(key.toString())) {
            throw new RuntimeException("此公司的服务还没有开通，请稍后再试") ;
        }
        return key;
    }

    public static boolean isExistDataSource(String key) {
        return dataSourceMap.containsKey(key);
    }
}
